package com.zyf.security.config;

import com.zyf.security.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/*
认证      //从你输入的东西里获得，然后查数据库，密码会自动对比。
 */
@Component
public class MyUserDetailService implements UserDetailsService {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    UserServiceImpl userService;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        com.zyf.security.entities.User user = userService.getUser(username);
        if (user == null) {
            return null;
        }
        List<String> role = userService.getRole(username);
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 角色必须以`ROLE_`开头，数据库中没有，则在这里加
        for (String item : role) {
            //把数据库中username对应的角色表放进去
            authorities.add(new SimpleGrantedAuthority("ROLE_"+item));
        }

        return new User(username,new BCryptPasswordEncoder().encode(user.getPassword()), authorities);
    }
}
